import base64
import json

from captcha.views import CaptchaStore, captcha_image
from django.http import HttpResponse
from rest_framework import viewsets
from rest_framework.response import Response
from rest_framework.views import APIView

from firepark_admin.models import Userinfo, use_records


# Create your views here.
class ImageView(APIView):
    def get(self, request):
        hashkey = CaptchaStore.generate_key()
        try:
            # 获取图片id
            id_ = CaptchaStore.objects.filter(hashkey=hashkey).first().id
            print(id_)
            imgage = captcha_image(request, hashkey)
            # 将图片转换为base64
            image_base = base64.b64encode(imgage.content)
            json_data = json.dumps({"id": id_, "image_base": image_base.decode('utf-8')})
        except:
            json_data = None
        return HttpResponse(json_data, content_type="application/json")


from .serlizers import Warehousingserlizer


class xinxiviewset(viewsets.ModelViewSet):
    queryset = use_records.objects.all()
    serializer_class = Warehousingserlizer

    def list(self, request, *args, **kwargs):
        s = request.query_params.get("token")
        tokens = Userinfo.objects.filter(token=s).first()
        queryset = self.filter_queryset(self.get_queryset().filter(user=tokens))
        page = self.paginate_queryset(queryset)
        if page is not None:
            serializer = self.get_serializer(page, many=True)
            return self.get_paginated_response(serializer.data)

        serializer = self.get_serializer(queryset, many=True)
        return Response(serializer.data)
